package sdk.webview.fmc.com.fmcsdk.base;


import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import rx.Observable;
import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.activity.H5Activity;
import sdk.webview.fmc.com.fmcsdk.app.AppManager;
import sdk.webview.fmc.com.fmcsdk.bean.SystemSetting;
import sdk.webview.fmc.com.fmcsdk.check.HideLoadEvent;
import sdk.webview.fmc.com.fmcsdk.util.AndroidBug5497Workaround;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.FMCLog;
import sdk.webview.fmc.com.fmcsdk.util.Language;
import sdk.webview.fmc.com.fmcsdk.util.NetworkUtils;
import sdk.webview.fmc.com.fmcsdk.util.PreferencesHelper;
import sdk.webview.fmc.com.fmcsdk.view.FMCProgressDialog;

/**
 * Created by ydm on 2017/7/31.
 * activity基础类，继承此类需要分别实现getLayoutId,init,createPresenter三个方法来做初始化的工作，不需要继承onCreat方法
 * 此类是基于MVP架构，第一个泛型V需要继承BaseView接口,第二个泛型T继承BasePresenter
 * Presenter的生命周期交由此类进行管理， 如果子类要使用多个Presenter, 则需要自行管理生命周期.
 * 此类已经实现了BaseView中的抽象方法, 子类无需再实现, 如需自定可覆写对应的方法.
 */

public abstract class BaseActivity<V extends BaseView, T extends BasePresenter<V>> extends RxAppCompatActivity implements BaseView {
    protected T presenter;
    /**
     * 加载框
     */
    public FMCProgressDialog loadingDialog;
    /**
     * 首选项
     */
    public SharedPreferences sharedPrefs;
    /**
     * log日志，会将打印的日志存储到本地log文件
     */
    public FMCLog logger;
    /**
     * 上下文
     */
    public Context context;
    public static boolean isActive; //全局变量
    public boolean standard;
    public static int setLang = 0; //全局变量

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        context = this;
        if (context instanceof H5Activity) {
            initImmersionBar7575_67();
        } else {
            initImmersionBar7575();
        }


        if (this.getClass().isAnnotationPresent(BindEventBus.class)) {
            EventBus.getDefault().register(this);
        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            Window window = getWindow();
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            window.setStatusBarColor(Color.TRANSPARENT);
//        }


//        if (Build.VERSION.SDK_INT >= 21) {
//            View decorView = getWindow().getDecorView();
//            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            getWindow().setStatusBarColor(Color.TRANSPARENT);
//        }

        Log.e("shuchang", "--->" + this.getClass().getName());
        if (this.getClass().getName().equals("sdk.webview.fmc.com.fmcsdk.activity.H5Activity")) {
            AndroidBug5497Workaround.assistActivity(this);
//            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);//设置软键盘弹出遮盖其他布局
        }
        //将activity添加进管理器
        AppManager.getAppManager().addActivity(this);

        if (savedInstanceState != null) {
            recoveryData(this, savedInstanceState);
        }
        /**activity过渡动画*/
        //   overridePendingTransition(R.anim.slide_out_left, R.anim.slide_out_left);
        /**初始化首选项*/
        sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        standard = sharedPrefs.getBoolean(Constant.STANDARD, false);

        /**初始化log*/
        logger = FMCLog.getInstance(this);
        /**语言切换*/
        int language = sharedPrefs.getInt("lang", 0);
//        if (language != 0) {
        Language.switchLanguage(context, Language.getLocal(language));
//        }
//        /**绑定注解*/
//        ButterKnife.bind(this);
        /**创建presenter*/
        presenter = createPresenter();
        if (presenter != null) {
            presenter.attachView((V) this, logger);
            /**设置首选项*/
            presenter.setSharedPrefs(sharedPrefs);
        }
        /**初始化进度条*/
        loadingDialog = new FMCProgressDialog(this);

        init(savedInstanceState);
    }


    /**
     * 初始化布局
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 在此方法中可以进行初始化操作，等同于onCreat
     *
     * @param savedInstanceState
     */
    protected abstract void init(Bundle savedInstanceState);

    /**
     * 创建presenter
     *
     * @return
     */
    protected abstract T createPresenter();


    /**
     * 返回context实例
     *
     * @return
     */
    @Override
    public Context getViewContext() {
        return this;
    }

    /**
     * 获取editext的值
     *
     * @param editText
     * @return
     */
    public String getText(TextView editText) {
        return editText.getText().toString().trim();
    }

    /**
     * 显示和隐藏进度条
     */
    @Override
    public void showLoading() {
        try {
            if(NetworkUtils.isAvailable(context)){
                if (!loadingDialog.isShowing()&&!isFinishing() && !isDestroyed()) {
                    loadingDialog.show();
                }
            }else{
            if (!loadingDialog.isShowing()) {
                runOnUiThread(() -> {
                    loadingDialog.show();
                    if(loadingDialog.getView()!=null){
                        loadingDialog.getView().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if(loadingDialog!=null){
                                    if (!isFinishing() && !isDestroyed()) {
                                        loadingDialog.dismiss();
                                    }

                                }
                            }
                        },1000)  ;
                    }
                });

            }}
        }catch (Exception e){}

    }

    @Override
    public void hideLoading() {
        if (loadingDialog == null) return;
        loadingDialog.setText("");
//        Log.e("shuchang", "调用了hideLoading---->");
        runOnUiThread(() -> {
            if (loadingDialog.isShowing()) {
                loadingDialog.dismiss();
            }
        });

    }

    /**
     * 管理toast
     *
     * @param message
     */
    @Override
    public void ToastMessage(String message) {
//        toast(message);
        Toast mToast = Toast.makeText(context, null, Toast.LENGTH_SHORT);
        mToast.setText(message);
        mToast.show();
    }

    @Override
    public void ToastMessage(int message) {
//        toast(message);
        Toast mToast = Toast.makeText(context, null, Toast.LENGTH_SHORT);
        mToast.setText(message);
        mToast.show();
    }

    public void toast(String s) {
//        ToastMgr.show(s);
        Toast mToast = Toast.makeText(context, null, Toast.LENGTH_SHORT);
        mToast.setText(s);
        mToast.show();
    }


    /**
     * 没有数据的时候是否显示空的列表
     */
    @Override
    public void hideEmptyHint() {
    }

    @Override
    public void showEmptyHint() {
    }


    /**
     * activity数据恢复
     *
     * @param saveBundle 当前activity被系统回收时保存的数据
     */
    public void recoveryData(Context context, Bundle saveBundle) {
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        AppManager.getAppManager().addCacheActivity(this);
    }


    /**
     * 生命周期管理
     */
    @Override
    protected void onStart() {
        super.onStart();
        if (presenter != null) presenter.onViewStart();
    }

    @Override
    protected void onResume() {
        if (!isActive) {
            //app 从后台唤醒，进入前台
            isActive = true;
            if (standard) {
                isBackground(0);
            }
        }
        super.onResume();
//        JPushInterface.onResume(context);
        if (presenter != null) presenter.onViewResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //overridePendingTransition(0,0);
        if (presenter != null) presenter.onViewPause();
    }


    @Override
    protected void onStop() {
        if (!isAppOnForeground()) {
            //app 进入后台
            isActive = false;//记录当前已经进入后台
            if (standard) {
                String appName = getApplicationInfo().loadLabel(getPackageManager()).toString();
//                ToastMessage(appName + "正在后台运行");
                isBackground(1);
            }
        }
        super.onStop();

        if (presenter != null) presenter.onViewStop();
    }

    /**
     * 界面退出时的动画
     */
    @Override
    public void finish() {
        super.finish();
        // 使用 0 或者 android.R.anim.fade_in 和 android.R.anim.fade_out 等作为参数来取消或指定其他动画
        //overridePendingTransition(0, 0);
        //  overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (this.getClass().isAnnotationPresent(BindEventBus.class)) {
            EventBus.getDefault().unregister(this);
        }
        if (presenter != null) presenter.detachView();
        presenter = null;
        if(context instanceof H5Activity){
        }else {
            AppManager.getAppManager().finishActivity(this);
        }

    }

    /**
     * 当前生命周期结束的时候自动取消订阅，防止内存泄漏
     */
    @Override
    public <T> Observable.Transformer<T, T> bind() {
        return bindToLifecycle();
    }

    /**
     * APP是否处于前台唤醒状态
     *
     * @return
     */
    public boolean isAppOnForeground() {
        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    public void isBackground(int backgroundType) {
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        int language = sharedPrefs.getInt("lang", 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            config.setLocale(Language.getLocal(language));
        } else {
            config.locale = Language.getLocal(language);
        }
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    private static final int MIN_CLICK_DELAY_TIME = 2000;
    private long mLastClickTime;

    /**
     * 防抖
     *
     * @param v
     * @return
     */
    public boolean needIgnoreClick(View v) {
        long currentTime = System.currentTimeMillis();
        if (currentTime - mLastClickTime < MIN_CLICK_DELAY_TIME) {
            return true;
        }
        mLastClickTime = currentTime;
        return false;
    }

    public void initImmersionBar() {
        ImmersionBar.with(this)
                .statusBarDarkFont(false, 0.2f)
                .transparentNavigationBar()
                .init();
    }

    public void initImmersionBarTrue() {
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .transparentNavigationBar()
                .init();
    }

    public void initImmersionBar7575() {
        ImmersionBar.with(this)
                .statusBarDarkFont(false, 0.2f)
                .navigationBarEnable(false)
                .statusBarColor(R.color.color7575)
                .transparentNavigationBar()
                .init();
    }


    public void initImmersionBar7575_67() {
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .navigationBarEnable(false)
                .transparentNavigationBar()
                .init();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(HideLoadEvent str) {
        hideLoading();
    }

}
